<?php

namespace App\Http\Middleware;

use Closure;

class VerifyHttp
{
    use \App\Traits\Rsa;
    /** 验证crm、金贝等系统的http请求
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        //获取sign
        $sign = $request->input('sign');
        $sign = str_replace(' ','+',$sign);

        $data = $request->all();

        error_log(date('Y-m-d H:i:s') . ' ' . print_r($data,1),3,base_path() . '/storage/logs/http.log');

        unset($data['sign']);

        $str = http_build_query($data);

        if(!self::verify($str,$sign)){
            error_log(date('Y-m-d H:i:s') . "签名错误\n" ,3,base_path() . '/storage/logs/http.log');
            echo json_encode([
                'code' => 401,
                'message' => 'sign error',
                'data' => null
            ]);exit;
        }
        return $next($request);
    }
}
